/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mabi.frontend.appbuilder.modulemanager;

import com.mabi.modular.MabiConstants;
import com.mabi.modular.install.modules.IModuleDefinition;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author User
 */
public class ModuleLoader {

    List<IModuleDefinition> modules = null;

    /**
     * Uses jndi api to discover modules that have been installed during the application deployment.
     * @return
     * @throws NamingException 
     */
    public List<IModuleDefinition> discoverInstalledModules() throws NamingException {
        lookupModules();
        return modules;
    }

    /**
     * Looks up the modules registered in the jndi
     * @throws NamingException 
     */
    private void lookupModules() throws NamingException {
        String[] registeredModules = getRegisteredModulesJndiKeys();
        if (null == modules) {
            modules = new ArrayList();
        }
        Context c = new InitialContext();
        for (String registeredModuleName : registeredModules) {
            String lookupString = MabiConstants.MODULE_LOOKUP_PREFIX + registeredModuleName + "/" + MabiConstants.MODULE_FILE_NAME;
            try {
                modules.add((IModuleDefinition) c.lookup(lookupString));
            } catch (NamingException ex) {
                System.out.println("FAILURE LOADING MODULE " + registeredModuleName);
                Logger.getLogger(ModuleLoader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /**
     * Extracts the jndi keys written in the System.properties by the modules at
     * install during the deployment.
     * @return 
     */
    private String[] getRegisteredModulesJndiKeys() {
        Properties properties = System.getProperties();
        List<String> jndiEntries = new ArrayList();
        Set<Object> keySet = properties.keySet();
        for (Object key : keySet) {
            if (((String) key).contains("module_")) {
                String entry = System.getProperty((String) key);
                if (entry != null) {
                    String[] entryItems = entry.split(",");
                    for (String entryItem : entryItems) {
                        String[] vars = entryItem.split("=>");
                        if (vars[0].equals("JNDI_KEY")) {
                            jndiEntries.add(vars[1]);
                        }
                    }
                }
            }
        }
        String[] jndiKeys = jndiEntries.toArray(new String[jndiEntries.size()]);
        for (String string : jndiKeys) {
            System.out.println("ENTRY " + string);
        }
        return jndiKeys;
    }
}
